<template>
  <a-result
    v-if="comments.length === 0"
    status="404"
    subtitle="还木有评论哦~ 点击评论输入第一条评论"
  />
  <a-comment
    v-for="(comment, index) in comments"
    :key="index"
    :author="comment.authorName"
    :datetime="comment.createTime"
  >
    <template #avatar>
      <a-avatar
        :image-url="comment.authorAvatar"
        trigger-type="mask"
        @click="handleToUserInfo(comment.authorId)"
      >
        <template #trigger-icon>
          <icon-user />
        </template>
      </a-avatar>
    </template>
    <template #content>
      <MdPreview style="padding: 0; margin: 0" :modelValue="comment.content" />
    </template>
    <template #actions>
      <a-popover :popup-visible="activeReplyId === comment.id" trigger="click">
        <template #content>
          <a-textarea
            v-model="recoverComment.content"
            style="width: 250px; height: 100px"
            placeholder="请友好回复哦~"
          />
          <a-row class="pt-1.5">
            <a-col :flex="1" />
            <a-col :span="5.5">
              <a-button
                type="primary"
                style="text-align: right"
                :loading="submitting"
                @click="doRecoverComment(comment)"
              >
                提交
              </a-button>
            </a-col>
          </a-row>
        </template>
        <span class="action" @click="handleRecoverComment(comment)">
          <IconMessage />
          回复
        </span>
      </a-popover>
      <a-link
        v-if="!comment.expandedFlag && comment.children && comment.children.length > 0"
        class="action"
        @click="toggleExpand(comment, true)"
      >
        <IconDown />
        展开 ({{ comment.children.length }})
      </a-link>
      <span
        v-else-if="comment.expandedFlag"
        class="action"
        @click="toggleExpand(comment, false)"
      >
        <IconUp />
        收起
      </span>
    </template>
    <inner-post-comment
      v-if="comment.expandedFlag && comment.children && comment.children.length > 0"
      :comments="comment.children"
    />
  </a-comment>
</template>

<script setup lang="ts">
import { PropType, ref } from 'vue';
import { IconMessage } from '@arco-design/web-vue/es/icon';
import { MdPreview } from 'md-editor-v3';
import { Message } from '@arco-design/web-vue';
import router from '@/router';
import { OjPostCommentService } from '@/api/gen-api/services/OjPostCommentService.ts';
import { PostCommentVo } from '@/api/gen-api/models/post/PostCommentVo.ts';
import { PostCommentRequest } from '@/api/gen-api/models/post/PostCommentRequest.ts';

defineProps({
  comments: {
    type: Array as PropType<PostCommentVo[]>,
    default: () => []
  }
});

const recoverComment = ref<PostCommentRequest>({
  content: '',
  postId: 0,
  parentId: null
});

// 使用单独的响应式变量控制当前活跃的回复框
const activeReplyId = ref<string | null>(null);
const submitting = ref(false);

// 切换评论展开状态
const toggleExpand = (comment: PostCommentVo, state: boolean) => {
  comment.expandedFlag = state;
};

const handleRecoverComment = (comment: PostCommentVo) => {
  // 设置当前激活的回复ID
  activeReplyId.value = comment.id;
  
  // 准备回复数据
  recoverComment.value = {
    content: '',
    postId: Number(comment.postId),
    parentId: Number(comment.id)
  };
};

/**
 * 提交回复
 */
const doRecoverComment = (comment: PostCommentVo) => {
  if (!recoverComment.value.content || recoverComment.value.content.trim() === '') {
    Message.error('回复内容不能为空');
    return;
  }
  
  if (!recoverComment.value.postId || !recoverComment.value.parentId) {
    Message.error('回复参数错误');
    console.error('回复参数错误:', recoverComment.value);
    return;
  }
  
  console.log('提交回复:', {
    content: recoverComment.value.content,
    postId: recoverComment.value.postId,
    parentId: recoverComment.value.parentId
  });
  
  submitting.value = true;
  
  OjPostCommentService.save({
    content: recoverComment.value.content.trim(),
    postId: recoverComment.value.postId,
    parentId: recoverComment.value.parentId
  }).then(res => {
    if (res.result) {
      // 清空回复内容
      recoverComment.value.content = '';
      Message.success('回复成功');
      
      // 关闭回复框
      activeReplyId.value = null;
      
      // 获取更新后的子评论
      if (comment.id) {
        OjPostCommentService.listChildren(comment.id).then(res => {
          if (res.result) {
            comment.children = res.result;
            // 自动展开子评论
            comment.expandedFlag = true;
          } else {
            console.warn('获取子评论成功但数据为空');
          }
        }).catch(error => {
          console.error('获取子评论失败:', error);
          Message.error('获取子评论失败，请刷新重试');
        });
      }
    }
  }).catch(error => {
    console.error('回复提交失败:', error);
    Message.error('回复提交失败，请重试');
  }).finally(() => {
    submitting.value = false;
  });
};

const handleToUserInfo = (authorId: string) => {
  if (!authorId) return;
  
  router.push({
    name: 'UserInfo',
    query: {
      id: authorId
    }
  });
};
</script>

<style scoped lang="less">
.action {
  display: inline-block;
  padding: 0 4px;
  line-height: 24px;
  color: var(--color-text-1);
  cursor: pointer;
  background: transparent;
  border-radius: 2px;
  transition: all 0.1s ease;
}

.action:hover {
  background: var(--color-fill-3);
}
</style>
